package com.epfresh.supplier.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.epfresh.api.dialog.TimePickerDialog;
import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.StatusEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.http.RequestManager;
import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.utils.CashierInputFilter;
import com.epfresh.api.utils.CustomDialog;
import com.epfresh.api.utils.DateUtil;
import com.epfresh.api.utils.FormatUtil;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.CommonInputItem;
import com.epfresh.supplier.R;
import com.epfresh.supplier.entity.CornerTag;
import com.epfresh.supplier.entity.Promotion;
import com.epfresh.supplier.entity.PromotionCondition;
import com.epfresh.supplier.view.tag.FlowLayout;
import com.epfresh.supplier.view.tag.TagAdapter;
import com.epfresh.supplier.view.tag.TagFlowLayout;
import com.google.gson.Gson;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class ProductSecKillActivity extends BaseActivity {


    private TextView tvPromotionPrice;
    private TextView tvPromotionPriceUnit;
    private EditText edPromotionPrice;

    private TextView tvLimitTitle;
    private TextView tvLimitUnit;
    private EditText edLimit;

    private TextView tvPromotionCountTitle;
    private TextView tvPromotionCountUnit;
    private EditText edPromotionCount;

    private CommonInputItem ciStartTime;
    private CommonInputItem ciEndTime;
    private TagFlowLayout tagCorner;
    private TagAdapter<CornerTag> adapterCorner;
    private List<CornerTag> listCorner = new ArrayList<>();

    private TagFlowLayout tagSecKill;
    private TagAdapter<String> adapterSecKill;
    private List<String> listSecKill = new ArrayList<>();

    private TextView tvBtn;
    String chargeUnit;
    double incr;
    String moq;
    String price;
    String productId;
    Promotion promotion;
    String inventory;
    Map<Integer, View> mapView = new HashMap<>();
    boolean isStartTimeCanEdit = true;
    boolean isDialog = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null){
            getIntent().putExtra("chargeUnit",savedInstanceState.getString("chargeUnit"));
            getIntent().putExtra("productId",savedInstanceState.getString("productId"));
            getIntent().putExtra("promotion",savedInstanceState.getString("promotion"));
            getIntent().putExtra("moq",savedInstanceState.getString("moq"));
            getIntent().putExtra("incr",savedInstanceState.getDouble("incr"));
            getIntent().putExtra("inventory",savedInstanceState.getString("inventory"));
            getIntent().putExtra("price",savedInstanceState.getString("price"));
            getIntent().putExtra("promotionStatus", savedInstanceState.getString("promotionStatus"));
        }
        setContentView(R.layout.activity_seckill);
        toolbarTitle.setText("秒杀");
        ivBack.setVisibility(View.VISIBLE);
        tvBack.setVisibility(View.VISIBLE);


        String promotionStatus = getIntent().getStringExtra("promotionStatus");
        if ("2".equals(promotionStatus)) {
            isStartTimeCanEdit = false;
        } else {
            isStartTimeCanEdit = true;
        }
        chargeUnit = getIntent().getStringExtra("chargeUnit");
        moq = getIntent().getStringExtra("moq");
        incr = getIntent().getDoubleExtra("incr",0d);
        inventory = getIntent().getStringExtra("inventory");
        price = getIntent().getStringExtra("price");
        String promotionStr = getIntent().getStringExtra("promotion");
        if (promotionStr != null && !"".equals(promotionStr)){
            promotion = new Gson().fromJson(promotionStr,Promotion.class);
        }
        productId = getIntent().getStringExtra("productId");
        if ("2".equals(promotionStatus) && promotion != null) {
            isDialog = true;
        } else {
            isDialog = false;
        }
        //初始化view
        initView();
        //加载数据
        requestTagList();

    }

    int tagW;

    private void initView() {
        tvPromotionPrice = (TextView) findViewById(R.id.tv_promotion_price);
        tvPromotionPriceUnit = (TextView) findViewById(R.id.tv_promotion_price_unit);
        edPromotionPrice = (EditText) findViewById(R.id.ed_promotion_price);

        tvLimitTitle = (TextView) findViewById(R.id.tv_limit_title);
        tvLimitUnit = (TextView) findViewById(R.id.tv_limit_unit);
        edLimit = (EditText) findViewById(R.id.ed_limit);

        tvPromotionCountTitle = (TextView) findViewById(R.id.tv_promotion_count_title);
        tvPromotionCountUnit = (TextView) findViewById(R.id.tv_promotion_count_unit);
        edPromotionCount = (EditText) findViewById(R.id.ed_promotion_count);

        ciStartTime = (CommonInputItem) findViewById(R.id.ci_start_time);
        ciEndTime = (CommonInputItem) findViewById(R.id.ci_end_time);
        tagCorner = (TagFlowLayout) findViewById(R.id.t_tag);
        tagSecKill = (TagFlowLayout) findViewById(R.id.t_activity_tag);

        tvBtn = (TextView) findViewById(R.id.tv_btn);
        tvBtn.setOnClickListener(this);
        ciStartTime.setOnClickListener(this);
        ciEndTime.setOnClickListener(this);

        String s = "秒杀价 <font color=\"#ff0000\">*</font>";
        tvPromotionPrice.setText(Html.fromHtml(s));
        s = "秒杀数量（每场） <font color=\"#ff0000\">*</font>";
        tvPromotionCountTitle.setText(Html.fromHtml(s));

        tagW = LocalDisplay.SCREEN_WIDTH_PIXELS - LocalDisplay.dp2px(42);
        tagW /= 3;

        adapterCorner = new TagAdapter<CornerTag>(listCorner) {
            @Override
            public View getView(FlowLayout parent, int position, CornerTag s) {
                ViewGroup v = (ViewGroup) LayoutInflater.from(ProductSecKillActivity.this).inflate(R.layout.corner_tag,
                        parent, false);
                ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) v.findViewById(R.id.rl_content).getLayoutParams();
                lp.width = tagW;
                lp.height = tagW * 3 / 4;

                ImageView ivBg = (ImageView) v.findViewById(R.id.iv_bg);
                ImageView ivCorner = (ImageView) v.findViewById(R.id.iv_corner);
                ImageView ivSelect = (ImageView) v.findViewById(R.id.iv_select);
                ViewGroup.LayoutParams lp2 = ivCorner.getLayoutParams();
                lp2.width = tagW / 3;

                if (position < listCorner.size()) {
                    CornerTag cornerTag = listCorner.get(position);
                    if (cornerTag.isSelect()) {
                        ivSelect.setVisibility(View.VISIBLE);
                    } else {
                        ivSelect.setVisibility(View.INVISIBLE);
                    }
                }

                ImageLoader.getInstance().displayImage(s.getImageUrl(), ivCorner);
                mapView.put(position, ivSelect);
                return v;
            }
        };
        tagCorner.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                int cnt = 0;
                for (int i=0;i<listCorner.size();i++){
                    if (i ==position){
                        continue;
                    }
                    CornerTag cornerTag = listCorner.get(i);
                    cornerTag.setSelect(false);
                    View v = mapView.get(i);
                    if (v != null) {
                        v.setVisibility(View.INVISIBLE);
                    }
                    if (cornerTag.isSelect()){
                        cnt++;
                    }
                }
                if (position < listCorner.size()) {
                    CornerTag cornerTag = listCorner.get(position);
//                    if (!cornerTag.isSelect()){
//                        if (cnt >= 1){
//                            toast("最多只能选择"+1 + "个角标");
//                            return true;
//                        }
//                    }
                    cornerTag.setSelect(!cornerTag.isSelect());
                    ImageView ivSelect = (ImageView) view.findViewById(R.id.iv_select);


                    if (cornerTag.isSelect()) {
                        ivSelect.setVisibility(View.VISIBLE);
                    } else {
                        ivSelect.setVisibility(View.INVISIBLE);
                    }

                }
//                adapterCorner.notifyDataChanged();
                return true;
            }
        });
        tagCorner.setAdapter(adapterCorner);


        adapterSecKill = new TagAdapter<String>(listSecKill) {
            @Override
            public View getView(FlowLayout parent, int position, String homeCommTag) {
                TextView tv = (TextView) LayoutInflater.from(ProductSecKillActivity.this).inflate(R.layout.sec_kill_tag,
                        parent, false);


                ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) tv.getLayoutParams();
                lp.width = (LocalDisplay.SCREEN_WIDTH_PIXELS - LocalDisplay.dp2px(47)) / 2;
//                lp.leftMargin = LocalDisplay.dp2px(8);
//                lp.topMargin = LocalDisplay.dp2px(10);
//
//
//                lp.height = LocalDisplay.dp2px(30);
                tv.setLayoutParams(lp);
                tv.setText(homeCommTag);
                return tv;
            }
        };

        tagSecKill.setAdapter(adapterSecKill);
        CashierInputFilter cashierInputFilter = new CashierInputFilter();
        cashierInputFilter.MAX_VALUE = 10000;
        edPromotionPrice.setFilters(new InputFilter[]{cashierInputFilter});
        cashierInputFilter = new CashierInputFilter();
        cashierInputFilter.MAX_VALUE = 1000000;
        edLimit.setFilters(new InputFilter[]{cashierInputFilter});
        cashierInputFilter = new CashierInputFilter();
        cashierInputFilter.MAX_VALUE = 1000000;
        edPromotionCount.setFilters(new InputFilter[]{cashierInputFilter});
        initData();

    }

    private void initData(){
        tvPromotionPriceUnit.setText("元/"+chargeUnit);
        tvLimitUnit.setText(chargeUnit +"/场");
        tvPromotionCountUnit.setText(chargeUnit);
        if (promotion != null){
            edLimit.setText(promotion.getQuantityPerAccount());
            edLimit.setSelection(edLimit.length());
            edPromotionCount.setText(promotion.getTotalQuantity());
            edPromotionCount.setSelection(edPromotionCount.length());
            String beginTime = promotion.getBeginTime();
            String endTime = promotion.getEndTime();

            ciStartTime.setContentText(beginTime);
            ciEndTime.setContentText(endTime);
            edPromotionPrice.setText(promotion.getPrice());
            edPromotionPrice.setSelection(edPromotionPrice.length());

            Set<Integer> set = new HashSet<>();
            List<String> spikeTime = promotion.getSpikeTime();
            if (listSecKill != null && spikeTime != null  && spikeTime.size() > 0){
                for (int i =0;i<listSecKill.size();i++){
                    String s = listSecKill.get(i);
                    if (s != null){
                        for (int j =0 ;j<spikeTime.size() ;j++){
                            String s1 = spikeTime.get(j);
                            if (s.equals(s1)){
                                set.add(i);
                            }
                        }
                    }
                }

                adapterSecKill.setSelectedList(set);
            }

            String markId = promotion.getMarkId();
            if (listCorner != null && markId != null && !"".equals(markId)){
                for (int i = 0;i<listCorner.size();i++){
                    CornerTag cornerTag = listCorner.get(i);
                    if (markId.equals(cornerTag.getId())){
                        cornerTag.setSelect(true);
                        adapterCorner.notifyDataChanged();
                        return;
                    }
                }
            }
        }else {
            String beginTime = "";
            String endTime = "";

            if (beginTime == null || "".equals(beginTime)){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Calendar calendar = Calendar.getInstance();
                calendar.setTimeInMillis(System.currentTimeMillis());
                calendar.add(Calendar.DAY_OF_MONTH,1);
                beginTime = sdf.format(calendar.getTime());
                if (endTime == null || "".equals(endTime)){
                    calendar.add(Calendar.DAY_OF_MONTH,6);
                    endTime = sdf.format(calendar.getTime());
                }
            }

            ciStartTime.setContentText(beginTime);
            ciEndTime.setContentText(endTime);
        }
    }

    private void initCondition(PromotionCondition promotionCondition) {
        if (promotionCondition != null) {
            List<CornerTag> promotionMark = promotionCondition.getSpikeMark();
            if (promotionMark != null && promotionMark.size() > 0) {
                listCorner.clear();
                listCorner.addAll(promotionMark);
            }

            List<String> spikeTime = promotionCondition.getSpikeTime();
            if (spikeTime != null && spikeTime.size() > 0) {
                listSecKill.clear();
                listSecKill.addAll(spikeTime);
            }
            initData();
            adapterCorner.notifyDataChanged();
            adapterSecKill.notifyDataChanged();
        }
    }

    private void openStartTime(String time) {
        TimePickerDialog timeDialog = new TimePickerDialog(this);


        timeDialog.setTitle("开始日期");

        timeDialog.setOnPositiveClickListener(new TimePickerDialog.OnPositiveClickListener() {
            @Override
            public void onPositiveClickListener(int index, String data) {
                ciStartTime.setContentText(data);
            }
        });

        timeDialog.setCurrentDate(time);

        timeDialog.show();
    }

    private void openEndTime(String time) {
        TimePickerDialog timeDialog = new TimePickerDialog(this);


        timeDialog.setTitle("结束日期");

        timeDialog.setOnPositiveClickListener(new TimePickerDialog.OnPositiveClickListener() {
            @Override
            public void onPositiveClickListener(int index, String data) {
                ciEndTime.setContentText(data);
            }
        });

        timeDialog.setCurrentDate(time);

        timeDialog.show();
    }



    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.ci_start_time:

                if (isStartTimeCanEdit) {
                    openStartTime(ciStartTime.getContentText());
                }else {
//                    toast("");
                }
                break;
            case R.id.ci_end_time:
                openEndTime(ciEndTime.getContentText());
                break;
            case R.id.tv_btn:
                save();
                break;
        }
    }


    CustomDialog.Builder builder;


    private void postSecKill(final Promotion p) {

        if (builder == null) {
            builder = new CustomDialog.Builder(this);

        }


        String s = "修改内容需下个场次生效,请知悉!";

        builder.setTitleVisible(false).setMessage(s)//设置显示的内容
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                        requestPromotionModify(p);
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {//响应事件
                dialog.dismiss();
            }

        });//在按键响应事件中显示此对话框

        builder.create().show();

    }


    private void save() {


        String price = edPromotionPrice.getText().toString();
        String limit = edLimit.getText().toString();
        String count = edPromotionCount.getText().toString();

        String startTime = ciStartTime.getContentText();
        String endTime = ciEndTime.getContentText();

        String markId = null;
        for (int i = 0;i<listCorner.size();i++){

            CornerTag cornerTag = listCorner.get(i);
            if (cornerTag.isSelect()){
                markId = cornerTag.getId();
            }
        }

        List<String> spikeTime= null;
        Set<Integer> set = tagSecKill.getSelectedList();
        for (Integer i:set){
            if (i < listSecKill.size()){
                if (spikeTime == null){
                    spikeTime = new ArrayList<>();
                }
                spikeTime.add(listSecKill.get(i));
            }
        }

        if (TextUtils.isEmpty(price)){
            toast("请填写秒杀价");
            return;
        }

        if (!isPriceRight(price,this.price)){
            toast("秒杀价要小于商品原价");
            return;
        }
        if("0".equals(FormatUtil.subZeroAndDot(price))){
            toast("请填写大于0的秒杀价");
            return;
        }
        if (TextUtils.isEmpty(count)){
            toast("请填写秒杀数量");
            return;
        }
        if("0".equals(FormatUtil.subZeroAndDot(count))){
            toast("请填写大于0的秒杀数量");
            return;
        }

        if (limit != null && !"".equals(limit) && !checkLimit(limit)){
            toast("限购数量已校准");
            limit = edLimit.getText().toString();
            return;
        }
        if("0".equals(FormatUtil.subZeroAndDot(limit))){
            toast("请填写大于0的限购数量");
            return;
        }
        if (TextUtils.isEmpty(startTime)){
            toast("请选择开始日期");
            return;
        }
        if (TextUtils.isEmpty(endTime)){
            toast("请选择结束日期");
            return;
        }
        if (isStartTimeCanEdit) {
            int t = DateUtil.compare(startTime, DateUtil.getTodayStr());
            if (!(t == -1 || t == 0)) {
                toast("开始日期不能早于今天");
                return;
            }
        }
        int c = DateUtil.compare(endTime, startTime);
        if (!(c == -1 || c==0 )){
            toast("结束日期不能早于开始日期");
            return;
        }
        if (spikeTime == null || spikeTime.size() == 0){
            toast("请选择活动场次");
            return;
        }
        if (TextUtils.isEmpty(markId)){
            toast("请选择角标");
            return;
        }
        if (!checkCount(count)) {
            toast("秒杀数量已校准");
            count = edPromotionCount.getText().toString();
            return;
        }
        if (!isMumRight()) {
            return;
        }

        Promotion p = new Promotion();
        p.setProductSpecId(productId);
        if (promotion != null){
            p.setId(promotion.getId());
        }

        if ("".equals(limit)){
            limit = null;
        }
        p.setPrice(price);
        p.setQuantityPerAccount(limit);
        p.setTotalQuantity(count);
        p.setSpikeTime(spikeTime);
        p.setBeginTime(startTime);
        p.setEndTime(endTime);
        p.setMarkId(markId);
        p.setType("2");
        p.setStoreId(BaseApplication.getInstance().getStoreId());
        if (productId != null && !"".equals(productId)) {
            if (isDialog){
                toast("修改内容仅对未进行场次有效");
            }
            requestPromotionModify(p);
        } else {
            Intent intent = new Intent();
            intent.putExtra("promotion", new Gson().toJson(p));
            setResult(RESULT_OK, intent);
            finish();
        }
    }

    private boolean isPriceRight(String price ,String priceO){

        try {

            Double aDouble = Double.valueOf(price);
            Double bDouble = Double.valueOf(priceO);

            if (FormatUtil.remainderZero(bDouble,aDouble) > 0){
                return true;
            }
        }catch (Exception e){

        }

        return false;

    }

    private boolean isMumRight() {

        String limit = edLimit.getText().toString();
        String count = edPromotionCount.getText().toString();


        int i = getAmount();

        Double aLimit = null;
        if (limit != null && !"".equals(limit)) {
            aLimit = Double.valueOf(limit);
        }
        Double aCount = Double.valueOf(count);

        Double aInventory = getInventory();
//            if (inventory != null && !"".equals(inventory)) {
//                aInventory = Double.valueOf(inventory);
//            }

        if (aInventory != null) {
            Log.e("p","aInventory:"+aInventory);
            Log.e("p","getAmount():"+getAmount());
            if (aCount * i > aInventory) {
                toast("秒杀数量不能大于库存");
                return false;
            }

            if (aLimit != null && aLimit > aCount) {
                toast("限购数量不能大于秒杀数量");
                return false;
            }
        }



        return true;
    }

    private int getAmount() {
        try {
            String startTime = ciStartTime.getContentText();
            String endTime = ciEndTime.getContentText();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date sd = sdf.parse(startTime);
            Date ed = sdf.parse(endTime);
            int i = DateUtil.differentDays(sd, ed);
            int c = 1;
            if (promotion !=null){
                List<String> spikeTime = promotion.getSpikeTime();
                if (spikeTime !=null && spikeTime.size() >0){
                    c = spikeTime.size();
                }
            }
            return (Math.abs(i) + 1) *c;
        } catch (ParseException e) {
            e.printStackTrace();

            return 1;
        }
    }

    private Double getInventory() {
        Double aInventory = null;
        if (inventory != null && !"".equals(inventory)) {
            aInventory = Double.valueOf(inventory);
        }

        return aInventory;
    }

    private boolean checkCount(String s) {


        double min = getMoq();

        double cnt = min;
        if (s.length() > 0) {
            cnt = Double.valueOf(s);
        }

        Log.e("cnt:", "min:" + min);
        Log.e("cnt:", "incr:" + incr);
        Log.e("cnt:", "cnt:" + cnt);
        if (cnt < 0.01 || cnt < min) {
//            T.toast("不能少于"+FormatUtil.subZeroAndDot(min+""));
            cnt = FormatUtil.countFormat(cnt, incr, min);
            edPromotionCount.setText(FormatUtil.subZeroAndDot(cnt + ""));
            edPromotionCount.setSelection(edPromotionCount.getText().length());
            return false;
        }


        incr = incr < 0.01 ? min : incr;


        if (FormatUtil.isRemainder(cnt, incr, min)) {
            Double aInventory = getInventory();
            int i = getAmount();
            if (aInventory != null && cnt > aInventory / i) {
                cnt = FormatUtil.countFormat(cnt, incr, min, aInventory);
            } else {
                cnt = FormatUtil.countFormat(cnt, incr, min);
            }
            edPromotionCount.setText(FormatUtil.subZeroAndDot(cnt + ""));
            edPromotionCount.setSelection(edPromotionCount.getText().length());
            return false;
        }
        return true;
    }



    private double getMoq(){
        try {
            Double aDouble = Double.valueOf(moq);
            if (aDouble != null){
                return aDouble;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return incr;
    }


    private boolean checkLimit(String s){


        double min = getMoq();

        double cnt = min;
        if (s.length() > 0) {
            cnt = Double.valueOf(s);
        }

        Log.e("cnt:","min:"+min);
        Log.e("cnt:","incr:"+incr);
        Log.e("cnt:","cnt:"+cnt);
        if (cnt < 0.01 || cnt < min) {
            T.toast("不能少于"+ FormatUtil.subZeroAndDot(min+""));
            cnt = FormatUtil.countFormat(cnt,incr,min);
            edLimit.setText(FormatUtil.subZeroAndDot(cnt + ""));
            edLimit.setSelection(edLimit.getText().length());
            return false;
        }



        incr = incr < 0.01 ? min : incr;

        if (FormatUtil.isRemainder(cnt,incr,min)) {
            cnt = FormatUtil.countFormat(cnt,incr,min);

            edLimit.setText(FormatUtil.subZeroAndDot(cnt + ""));
            edLimit.setSelection(edLimit.getText().length());
            return false;
        }
        return true;
    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString("inventory",getIntent().getStringExtra("inventory"));
        outState.putString("chargeUnit",getIntent().getStringExtra("chargeUnit"));
        outState.putString("productId",getIntent().getStringExtra("productId"));
        outState.putString("promotion",getIntent().getStringExtra("promotion"));
        outState.putString("price",getIntent().getStringExtra("price"));
        outState.putString("moq",getIntent().getStringExtra("moq"));
        outState.putString("promotionStatus", getIntent().getStringExtra("promotionStatus"));
        outState.putDouble("incr",getIntent().getDoubleExtra("incr",0d));
        super.onSaveInstanceState(outState);
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 0x45 && resultCode == RESULT_OK) {

        }
    }

    RequestTag requestTag;

    private void requestTagList() {
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_promotion_conditions);
        if (requestTag == null) {
            requestTag = new RequestTag();
            requestTag.tag = com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_promotion_conditions;
        }

        requestTag.type = RequestTag.TYPE_CURRENT;

        request(RequestEntityMapSupply, requestTag, onTagListRequestListener);

    }

    private PromotionCondition promotionCondition;
    private OnRequestListener<PromotionCondition> onTagListRequestListener = new OnRequestListener<PromotionCondition>() {
        @Override
        public PromotionCondition jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, PromotionCondition.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
//            showExceptionView(R.mipmap.icon_error, "网络错误", HttpRequest.FAIL_NET_FAULT);
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
//            showExceptionView(R.mipmap.icon_error, arg + "", HttpRequest.FAIL_NET_FAULT);
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<PromotionCondition> response, Object tag) {

//            showMainView();

            hideProgressDialog();
            PromotionCondition responseElement = response.getResponseElement();

            if (responseElement != null) {
                promotionCondition = responseElement;
                initCondition(promotionCondition);

            }
        }
    };

    RequestTag requestPromotionModify;

    private void requestPromotionModify(Promotion promotion) {
        RequestEntitySupply<Promotion> RequestEntityMapSupply = new RequestEntitySupply();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_promotion_modify);
        RequestEntityMapSupply.setParameters(promotion);
        if (requestPromotionModify == null) {
            requestPromotionModify = new RequestTag();
            requestPromotionModify.tag = com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_promotion_modify;
        }

//        requestPromotionModify.type = RequestTag.TYPE_CURRENT;

        request(RequestEntityMapSupply, requestPromotionModify, onPromotionModifyRequestListener);

    }

    private OnRequestListener<StatusEntity> onPromotionModifyRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
//            showExceptionView(R.mipmap.icon_error, "网络错误", HttpRequest.FAIL_NET_FAULT);
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
//            showExceptionView(R.mipmap.icon_error, arg + "", HttpRequest.FAIL_NET_FAULT);
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {

//            showMainView();

            hideProgressDialog();
            StatusEntity responseElement = response.getResponseElement();

            if (responseElement.isSuccess()) {

                setResult(RESULT_OK);
                finish();
            }
        }
    };


    @Override
    protected void onDestroy() {
        RequestManager.getInstance().cancel(requestTag);
        RequestManager.getInstance().cancel(requestPromotionModify);
        super.onDestroy();
    }
}

